package com.freelancer.musicinstruction.activity.delegates;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import android.os.Handler;
import android.util.Log;

public class ThreadManager {
	
	private static final String TAG = ThreadManager.class.getSimpleName();
		
	private ExecutorService	executor;

	private Runnable		updateTask;

	private Handler			guiThread;

	@SuppressWarnings(value = "unchecked")
	private Future			taskPending;


	private ThreadManager() {
		guiThread = new Handler();
		executor = Executors.newCachedThreadPool();
		Log.d(TAG, "singleton created");
	}
	
	private static class ThreadManagerSigleton {
	     private static final ThreadManager INSTANCE = new ThreadManager();
	}
	
	public static ThreadManager getInstance() {
	     return ThreadManagerSigleton.INSTANCE;
	}

	public void submitTask(Runnable task) {
		// Cancel previous call if there is one
		if (taskPending != null) {
			taskPending.cancel(true);
		}
		
		taskPending = executor.submit(task);
	}

	/** Request a post on the Gui Thread to start after a short delay */
	public void postDelayedOnGuiThread(long delayMillis, Runnable task) {
		// Cancel previous update if it hasn't started yet
		if (updateTask != null) {
			guiThread.removeCallbacks(updateTask);
		}

		updateTask = task;

		// Start an update if nothing happens after a few milliseconds
		guiThread.postDelayed(updateTask, delayMillis);
	}

	/** Request a post on the Gui Thread */
	public void postOnGuiThread(Runnable task) {
		// Cancel previous update if it hasn't started yet
		if (updateTask != null) {
			guiThread.removeCallbacks(updateTask);
		}

		updateTask = task;

		// Start an update
		guiThread.post(updateTask);
	}

	public void onDestroy() {
		// Terminate extra threads here
		executor.shutdownNow();
	}
	
}
